<?php
/**
 * Created by PhpStorm.
 * User: beijingwhg
 * Date: 2017/5/5
 * Time: 下午5:57
 */

namespace App\Http\Controllers\Admin;


use App\Events\Admin\Auth\Lockout;
use App\Events\Admin\Auth\Login;
use App\Http\Controllers\Controller;
use App\Models\AdminModel;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    use ThrottlesLogins;

    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function showLoginForm()
    {
        return view('admin.login');
    }

    public function login(AdminModel $adminModel)
    {
        //参数验证
        $this->validate($this->request, [
            'username' => 'required|max:20',
            'password' => 'required|min:5|max:12',
        ]);
        //获取数据
        $username = e($this->request->input('username'));
        $password = $this->request->input('password');
        //判断类型
        if (strpos($username, '@')) {
            $where = ['email'=>$username];
        } else {
            $where = ['phone'=>$username];
        }

        //获取用户
        $manager = $adminModel->where($where)->first();
        //用户名不存在
        if (!$manager) {
            return response()->json(['username'=>[config('self.errors.username-tip')]], 422);
        }
        //已经被锁定
        if (!$manager->status) {
            return response()->json(['username'=>[config('self.errors.locked')]], 423);
        }
        //最大尝试次数
        $maxAttempts = config('self.max-attempts');
        //太多次尝试
        if ($manager->attempts >= $maxAttempts) {
            event(new Lockout($this->request));

            return response()->json(['username'=>[config('self.errors.locked')]], 423);
        }
        //验证登录
        $granted = Auth::guard('admin')->attempt(array_merge($where, ['password'=>$password]), false);
        //判断结果
        if ($granted) {
            if ($manager->attempts) {
                $adminModel->where('admin_id', $manager->admin_id)->update(['attempts'=>0]);
            }

            event(new Login($manager, $this->request));

            $intend = $this->request->session()->pull('intend', config('self.errors.default-index'));

            return response()->json(['granted'=>true, 'url'=>$intend]);
        }
        //增加尝试次数
        $manager->increment('attempts');
        //错误通知
        $tips = sprintf(config('self.errors.password-tip'), ($maxAttempts - $manager->attempts));
        //返回失败
        return response()->json(['password'=>[$tips]], 423);
    }

    public function logout()
    {
        Auth::guard('admin')->logout();

        return redirect('/admin/login');
    }
}